package com.itheima.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pinda.base.BaseController;
import com.itheima.pinda.base.R;
import com.itheima.pinda.base.entity.SuperEntity;
import com.itheima.pinda.utils.SpringUtils;
import com.itheima.wms.dto.AreaDTO;
import com.itheima.wms.entity.AreaEntity;
import com.itheima.wms.entity.LocationEntity;
import com.itheima.wms.excel.service.AreaExcelService;
import com.itheima.wms.excel.service.impl.AreaExcelServiceImpl;
import com.itheima.wms.service.AreaService;
import com.itheima.wms.service.LocationService;
import com.itheima.wms.vo.AreaDetailVO;
import com.itheima.wms.vo.AreaLocationTreeVO;
import com.itheima.wms.vo.AreaOverviewVO;
import com.itheima.wms.vo.ImportResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.itheima.pinda.exception.code.ExceptionCode.BASE_VALID_PARAM;

/**
 * <p>
 * 前端控制器
 * 库区
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("/area")
@Api(value = "Area", tags = "库区")
public class AreaController extends BaseController {

    @Autowired
    private AreaService areaService;
    @Autowired
    private LocationService locationService;

    @Autowired
    private AreaExcelService areaExcelService;

    /**
     * 分页查询库区
     *
     * @param data 分页查询对象
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询库区", notes = "分页查询库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", dataType = "long", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示几条", dataType = "long", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "ascs", value = "正序排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "descs", value = "倒叙排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "data", value = "无效参数 字段可以使用前缀控制查询方式 gt_, ge_, lt_, le_, in_, like_, likeRight_, likeLeft_", dataType = "string", paramType = "none"),
            @ApiImplicitParam(name = "warehouseId", value = "仓库id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "temperatureType", value = "温度类型 常温:CW、冷藏:LC、恒温:HW", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bearingType", value = "承重类型 重型:ZX、中型:OX、轻型:QX", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "useType", value = "用途类型 入库缓存区：RKHCQ 出库缓存区：CKHCQ 存储区：CCQ  分拣区：FJQ 质检区：ZJQ", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "personId", value = "负责人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "personName", value = "负责人姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "联系电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "includedNum", value = "库位数量", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态 0 停用 1启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createUser", value = "创建人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "createName", value = "创建人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "updateUser", value = "更新人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "updateName", value = "更新人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "logicDel", value = "逻辑删除 0 删除", dataType = "Integer", paramType = "query"),
    })
    @GetMapping("/page")
    public R<IPage<AreaEntity>> page(@RequestParam Map data) {
        Page<AreaEntity> page = getPage();
        IPage<AreaEntity> areaPage = areaService.page(page, data);
        page.setRecords(areaPage.getRecords());
        return success(page);
    }

    @ApiOperation(value = "分页查询库区详细信息", notes = "分页查询库区详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", dataType = "long", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示几条", dataType = "long", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "warehouseName", value = "仓库名称", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "库区名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态 0 停用 1启用", dataType = "Integer", paramType = "query"),
    })
    @GetMapping("/pageDetail")
    public R<IPage<AreaDetailVO>> pageDetail(@RequestParam Map data) {
        Page<AreaDetailVO> page = getPage();
        IPage<AreaDetailVO> areaPage = areaService.pageDetail(page, data);
        page.setRecords(areaPage.getRecords());
        return success(page);
    }

    @ApiOperation(value = "查询全部库区", notes = "查询全部库区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ascs", value = "正序排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "descs", value = "倒叙排列字段（逗号分隔）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "data", value = "无效参数 字段可以使用前缀控制查询方式 gt_, ge_, lt_, le_, in_, like_, likeRight_, likeLeft_", dataType = "string", paramType = "none"),
            @ApiImplicitParam(name = "warehouseId", value = "仓库id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "temperatureType", value = "温度类型 常温:CW、冷藏:LC、恒温:HW", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bearingType", value = "承重类型 重型:ZX、中型:OX、轻型:QX", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "useType", value = "用途类型 入库缓存区：RKHCQ 出库缓存区：CKHCQ 存储区：CCQ  分拣区：FJQ 质检区：ZJQ", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "personId", value = "负责人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "personName", value = "负责人姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "联系电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "includedNum", value = "库位数量", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "ownerId", value = "货主id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态 0 停用 1启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createUser", value = "创建人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "createName", value = "创建人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "updateUser", value = "更新人id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "updateName", value = "更新人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", dataType = "java.time.LocalDateTime", paramType = "query"),
            @ApiImplicitParam(name = "logicDel", value = "逻辑删除 0 删除", dataType = "Integer", paramType = "query"),
    })
    @GetMapping("/list")
    public R<List<AreaEntity>> list(@RequestParam Map data) {
        List<AreaEntity> areaArray = areaService.list(data);
        return success(areaArray);
    }

    @ApiOperation(value = "查询库区库位树", notes = "查询库区库位树")
    @GetMapping("/tree")
    public R<List<AreaLocationTreeVO>> list(@RequestParam("仓库id") Long warehouseId) {
        LambdaQueryWrapper<AreaEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(AreaEntity::getWarehouseId, warehouseId);
        List<AreaEntity> areaEntities = areaService.list(wrapper);
        List<AreaLocationTreeVO> areaLocationTreeVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(areaEntities)) {
            areaLocationTreeVOS = areaEntities.stream().map(item -> {
                LambdaQueryWrapper<LocationEntity> locationWrapper = new LambdaQueryWrapper();
                locationWrapper.eq(LocationEntity::getAreaId, item.getId());
                List<LocationEntity> locationEntities = locationService.list(locationWrapper);
                List<AreaLocationTreeVO> children = locationEntities.stream().map(location -> AreaLocationTreeVO.builder().label(location.getName()).value(location.getId()).ownerId(location.getOwnerId()).build()).collect(Collectors.toList());
                return AreaLocationTreeVO.builder().label(item.getName()).value(item.getId()).children(children).build();
            }).collect(Collectors.toList());
        }
        return success(areaLocationTreeVOS);
    }

    /**
     * 查询库区
     *
     * @param id 主键id
     * @return 查询结果
     */
    @ApiOperation(value = "查询库区", notes = "查询库区")
    @GetMapping("/{id}")
    public R<AreaEntity> get(@PathVariable Long id) {
        return success(areaService.getById(id));
    }

    /**
     * 查询库区总览
     *
     * @param id 主键id
     * @return 查询结果
     */
    @ApiOperation(value = "查询库区总览", notes = "查询库区总览")
    @GetMapping("overview/{id}")
    public R<AreaOverviewVO> overview(@PathVariable Long id) {
        return success(areaService.overview(id));
    }

    /**
     * 新增库区
     *
     * @param data 新增对象
     * @return 新增结果
     */
    @ApiOperation(value = "新增库区", notes = "新增库区不为空的字段")
    @PostMapping
    public R<AreaEntity> save(@RequestBody @Validated(SuperEntity.Save.class) AreaDTO data) {
        areaService.save(data);
        return success(data);
    }

    /**
     * 修改库区
     *
     * @param data 修改对象
     * @return 修改结果
     */
    @ApiOperation(value = "修改库区", notes = "修改库区不为空的字段")
    @PutMapping
    public R<AreaEntity> update(@RequestBody @Validated(SuperEntity.Update.class) AreaDTO data) {
        areaService.updateById(data);
        return success(data);
    }

    /**
     * 删除库区
     *
     * @param ids 主键id
     * @return 删除结果
     */
    @ApiOperation(value = "删除库区", notes = "根据id物理删除库区")
    @DeleteMapping
    public R<Boolean> delete(@RequestParam("ids[]") List<Long> ids) {
        areaService.removeByIds(ids);
        return success();
    }

    @PostMapping("importExcel")
    @ApiOperation("导入")
    public R<? extends Object> importExcel(@RequestParam(value = "file") MultipartFile file) {
        if (file.isEmpty()) {
            return fail(BASE_VALID_PARAM.build("导入内容为空"));
        }
        Long begin = System.currentTimeMillis();
//        ImportResultVO importResultVO = areaService.importExcel(file);

        // 获取新对象
        areaExcelService = SpringUtils.getBean(AreaExcelServiceImpl.class);
        ImportResultVO importResultVO = areaExcelService.analysis(file);
        Long end = System.currentTimeMillis();

        log.info("导入excel 用时 :{}", (end - begin));
        return R.success(importResultVO);
    }
}
